﻿using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Aierp.Repository;
using Aierp.Utility.Core;
using Aierp.Utility;
using System.Threading.Tasks;
using Aierp.Repository.Models;
using Aierp.SystemEntities.System;
using Microsoft.AspNetCore.Http;

namespace Aierp.Controllers
{
    public class UserController : ControllerBase
    {
        IUserRepository Users { get; set; }
        SysVisitor SysVisitor { get; set; }
     
        public UserController(IUserRepository users, SysVisitor sysVisitor)
        {
            Users = users;
            SysVisitor = sysVisitor;
        }

        // GET: api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
           var model = Users.Find(SysVisitor.UserName);
           return model == null ? new string[] { } : new[] { model.UserName, model.TrueName };
        }

        [HttpGet("GetUserById")]
        public async Task GetUserById()
        {
            var request = HttpContext.Request;
            var keyId = request.Query["KeyId"];
            if (string.IsNullOrEmpty(keyId))
            {
                await WriteFailJson();
            }
            var user = Users.FindById(int.Parse(keyId));
            if( user == null)
            {
                await WriteFailJson();
                return;
            }
            await WriteResultJson(user);
        }

        [HttpGet("GetCurrentUser")]
        public async Task GetCurrentUser()
        {
            var user = Users.FindById(SysVisitor.CurrentUser.KeyId);
            //return user == null ? "" : JSONhelper.ToJson(user);
            if (user == null)
            {
                await WriteFailJson();
                return;
            }
            await WriteResultJson(user);
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetList")]
        public async Task GetList()
        {
            string userName = HttpContext.Request.Query["userName"];
            var pageParam = this.GetPageParam();
            await Response.WriteAsync(Users.GetList(pageParam.Order, pageParam.Limit, pageParam.Offset, userName));
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        // POST api/values
        [HttpPost]
        public async Task Post(string value)
        {
             //检查用户是否有权限操作
             if (!await CheckUser(SysVisitor)) return;

            //获取用户对象
            var user = GetModel<Sys_Users>();

            if (user.UserName.IsEmpty() || user.TrueName.IsEmpty())
            {
                await this.WriteSpecReasonJson("保存失败，错误信息如下：用户名或真实姓名不能为空！");
                return;
            }

            var result = Users.Add(user);

            if (result > 0)
            {
                await this.WriteSucessJson();
            }
            else if (result == -2)
            {
                await this.WriteSpecReasonJson("用户名已存在，请更换用户名！");
            }
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <returns></returns>
        [HttpPost("Update")]
        public async Task Update()
        {
            //检查用户是否有权限操作
            if (!await CheckUser(SysVisitor)) return;

            //获取用户对象
            var user = GetModel<Sys_Users>();

            if (user.UserName.IsEmpty() || user.TrueName.IsEmpty())
            {
                await this.WriteSpecReasonJson("保存失败，错误信息如下：用户名或真实姓名不能为空！");
                return;
            }

            if (Users.Update(user) > 0)
            {
                await this.WriteSucessJson();
            }
            else
            {
                await this.WriteFailJson();
            }
        }

        /// <summary>
        /// 更新我的信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("UpdateMyinfo")]
        public async Task UpdateMyinfo()
        {
            //获取用户对象
            var user = GetModel<Sys_Users>();
            if (user.KeyId != SysVisitor.CurrentUser.KeyId)
            {
                //检查用户是否有权限操作
                if (!await CheckUser(SysVisitor)) return;
            }

            if (user.UserName.IsEmpty() || user.TrueName.IsEmpty())
            {
                await this.WriteSpecReasonJson("保存失败，错误信息如下：用户名或真实姓名不能为空！");
                return;
            }

            if (Users.UpdateMyInfo(user) > 0)
            {
                await this.WriteSucessJson();
            }
            else
            {
                await this.WriteFailJson();
            }
        }

        /// <summary>
        /// 停用用户
        /// </summary>
        /// <param name="id"></param>
        // DELETE api/values/5
        [HttpDelete("{id}")]
        public async Task Delete(int id)
        {
            //检查用户是否有权限操作
             if (!await CheckUser(SysVisitor)) return;;

            if (id == 0)
            {
                await this.WriteSpecReasonJson("系统中没有这个用户！");
                return;
            }
            var result = Users.Remove(id);
            if (result > 0)
            {
                await this.WriteSucessJson();
            }
            else switch (result)
            {
                case -2:
                    await this.WriteSpecReasonJson("系统中找不到这个用户！");
                    break;
                case -9:
                    await this.WriteSpecReasonJson("admin账户不能删除！");
                    break;
            }
        }
        
        /// <summary>
        /// 重置密码
        /// </summary>
        [HttpPost("ResetPassWord")]
        public async Task ResetPassWord()
        {
            //检查用户是否有权限操作
             if (!await CheckUser(SysVisitor)) return;;
            var id = 0;

            int.TryParse(HttpContext.Request.Form["KeyId"],out id);
            if (id == 0)
            {
                await this.WriteSpecReasonJson("系统中没有这个用户！");
                return;
            }

            var result = Users.ResetPassWord(id);
            if (result > 0)
            {
                await this.WriteSucessJson();
            }
            else if (result == -2)
            {
                await this.WriteSpecReasonJson("系统中找不到这个用户！");
            }
            else if (result <= 0)
            {
                await this.WriteSpecReasonJson("重置失败，请使用初始密码登录，或联系管理员！");
            }
        }

        /// <summary>
        /// 更改密码
        /// </summary>
        [HttpPost("ChangePassWord")]
        public async Task ChangePassWord()
        {
            //获取用户对象
            var user = GetModel<PassWordModel>();
            if (user.KeyId != SysVisitor.CurrentUser.KeyId)
            {
                //检查用户是否有权限操作
                if (!await CheckUser(SysVisitor)) return;
            }

            if (user.OldPassword.IsEmpty() || user.NewPassword.IsEmpty() || user.UserName.IsEmpty())
            {
                await this.WriteSpecReasonJson("用户名或密码不能为空！");
                return;
            }

            var result = Users.ChangePassWord(user.KeyId, user.OldPassword, user.NewPassword);
            if (result > 0)
            {
                await this.WriteSucessJson();
                return;
            }
            switch (result)
            {
                case -2:
                    await this.WriteSpecReasonJson("系统中找不到这个用户！");
                    return;
                case -9:
                    await this.WriteSpecReasonJson("输入的旧密码不正确！");
                    return;
            }
            if (result <= 0)
            {
                await this.WriteSpecReasonJson("更改密码出现问题，请联系管理员！");
            }

        }

    }
}
